#!/usr/bin/env gosh
(use srfi-1)
(use sxml.ssax)
(use sxml.serializer)
(use sxml.tools)
(use sxml.sxpath)
(use sxml.tree-trans)
(use gauche.sequence)
(use gauche.process)
(use gauche.parseopt)

(define (main args)
  (load "./common.scm")
  (let-args (cdr args)
      ((path-i "i|itempath=s" "")
       (path-v "v|valuepath=s" "")
       (file   "f|file=s" #f)
       (cmd    "c|cmd=s" #f)
       (print-v "p" #f)
       (print-vonly "o" #f)
       (print-marked "m" #f))
    (define sxml (if file
		   (call-with-input-file file (lambda (in)
						(ssax:xml->sxml in '())))
		   (ssax:xml->sxml (current-input-port) '())))
    (define marked-value (sxpath "//mark/@v/text()"))
    (mark! sxml path-i path-v)
    (cond
     (print-v
       (for-each-with-index (lambda (i x)
			      (format #t "~a\t~d\n" x i))
			    (marked-value sxml)))
     (print-vonly
      (for-each (lambda (x)
		  (format #t "~a\n" x))
		(marked-value sxml)))
     (print-marked
      (print (srl:sxml->html sxml)))
     (cmd 
      (grep! sxml cmd)
      (print (srl:sxml->html (pre-post-order
			      sxml
			      `((mark . ,(lambda (x attr elems)
					   (if (assq 'filter (cdr attr))
					     elems
					     "")))
				(*text* . ,(lambda (trigger x) x))
				(*default* . ,(lambda x x)))))))
     (else
      (print (srl:sxml->html sxml))))))

(define (grep! sxml cmd)
  (define ht (make-hash-table 'string=?))
  (let ((items ((sxpath "//mark[@v]") sxml))
	(values ((sxpath "//mark/@v/text()") sxml)))
    (for-each-with-index (lambda (i x)
			   (hash-table-update! ht x (lambda (y)
						      (append y (list i)))
					       '()))
			 values)
    (let ((cmd-result (run-cmd2 cmd values)))
      (for-each (lambda (x)
		  (sxml:add-attr! (list-ref items x) '(filter "")))
		(map (lambda (x)
		       (hash-table-pop! ht x))
		     cmd-result)))))







